// pages/volunteer/messages.js
Page({
  data: {
    activeTab: 'system',
    showMoreModal: false,
    systemUnread: 3,
    noticeUnread: 2,
    commentUnread: 5,
    likeUnread: 1,
    
    systemMessages: [
      {
        id: 1,
        title: '密码修改通知',
        content: '您的账户密码已于2024-01-15 14:30成功修改，如非本人操作，请及时联系客服。',
        time: '2024-01-15 14:30',
        isRead: false,
        type: 'security'
      },
      {
        id: 2,
        title: '账户安全提醒',
        content: '检测到您的账户在新设备上登录，登录地点：北京市。如非本人操作，请及时修改密码。',
        time: '2024-01-14 09:15',
        isRead: false,
        type: 'security'
      }
    ],
    
    noticeMessages: [
      {
        id: 1,
        title: '春节志愿活动招募',
        content: '2024年春节即将到来，我们将在社区开展"温暖春节"志愿活动，现招募志愿者参与。',
        time: '2024-01-15 10:00',
        isRead: false,
        hasAction: true,
        action: 'join',
        actionText: '立即报名'
      }
    ],
    
    commentMessages: [
      {
        id: 1,
        userName: '张小明',
        userAvatar: '/images/avatar1.png',
        content: '这个活动很有意义，我也想参加！',
        targetContent: '春节志愿活动招募',
        time: '2024-01-15 15:30',
        isRead: false
      }
    ],
    
    likeMessages: [
      {
        id: 1,
        userName: '陈小华',
        userAvatar: '/images/avatar5.png',
        content: '点赞了您的活动分享',
        likedContent: '春节志愿活动招募',
        time: '2024-01-15 16:45',
        isRead: false
      }
    ]
  },

  onLoad(options) {
    this.loadMessages();
  },

  onShow() {
    this.updateUnreadCount();
  },

  loadMessages() {
    const messagesData = wx.getStorageSync('volunteerMessagesData');
    if (messagesData) {
      this.setData({
        systemMessages: messagesData.systemMessages || this.data.systemMessages,
        noticeMessages: messagesData.noticeMessages || this.data.noticeMessages,
        commentMessages: messagesData.commentMessages || this.data.commentMessages,
        likeMessages: messagesData.likeMessages || this.data.likeMessages
      });
    }
    this.updateUnreadCount();
  },

  updateUnreadCount() {
    const systemUnread = this.data.systemMessages.filter(msg => !msg.isRead).length;
    const noticeUnread = this.data.noticeMessages.filter(msg => !msg.isRead).length;
    const commentUnread = this.data.commentMessages.filter(msg => !msg.isRead).length;
    const likeUnread = this.data.likeMessages.filter(msg => !msg.isRead).length;

    this.setData({
      systemUnread,
      noticeUnread,
      commentUnread,
      likeUnread
    });
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  readMessage(e) {
    const { id, type } = e.currentTarget.dataset;
    const messagesKey = `${type}Messages`;
    const messages = this.data[messagesKey];
    
    const updatedMessages = messages.map(msg => {
      if (msg.id === id) {
        return { ...msg, isRead: true };
      }
      return msg;
    });

    this.setData({
      [messagesKey]: updatedMessages
    });

    this.updateUnreadCount();
    this.saveMessages();
  },

  handleAction(e) {
    const { action, id } = e.currentTarget.dataset;
    
    switch (action) {
      case 'join':
        wx.showModal({
          title: '报名确认',
          content: '确定要报名参加此活动吗？',
          success: (res) => {
            if (res.confirm) {
              wx.showToast({
                title: '报名成功',
                icon: 'success'
              });
            }
          }
        });
        break;
    }
  },

  markAllAsRead() {
    wx.showModal({
      title: '确认操作',
      content: '确定要将所有消息标记为已读吗？',
      success: (res) => {
        if (res.confirm) {
          const systemMessages = this.data.systemMessages.map(msg => ({ ...msg, isRead: true }));
          const noticeMessages = this.data.noticeMessages.map(msg => ({ ...msg, isRead: true }));
          const commentMessages = this.data.commentMessages.map(msg => ({ ...msg, isRead: true }));
          const likeMessages = this.data.likeMessages.map(msg => ({ ...msg, isRead: true }));

          this.setData({
            systemMessages,
            noticeMessages,
            commentMessages,
            likeMessages,
            systemUnread: 0,
            noticeUnread: 0,
            commentUnread: 0,
            likeUnread: 0
          });

          this.saveMessages();
          wx.showToast({
            title: '已全部标记为已读',
            icon: 'success'
          });
        }
      }
    });
  },

  showMoreOptions() {
    this.setData({
      showMoreModal: true
    });
  },

  hideMoreOptions() {
    this.setData({
      showMoreModal: false
    });
  },

  stopPropagation() {
    // 阻止事件冒泡
  },

  clearAllMessages() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有消息吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            systemMessages: [],
            noticeMessages: [],
            commentMessages: [],
            likeMessages: [],
            systemUnread: 0,
            noticeUnread: 0,
            commentUnread: 0,
            likeUnread: 0
          });
          this.saveMessages();
          this.hideMoreOptions();
          wx.showToast({
            title: '已清空所有消息',
            icon: 'success'
          });
        }
      }
    });
  },

  exportMessages() {
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none'
    });
    this.hideMoreOptions();
  },

  messageSettings() {
    wx.navigateTo({
      url: '/pages/volunteer/message-settings'
    });
    this.hideMoreOptions();
  },

  saveMessages() {
    const messagesData = {
      systemMessages: this.data.systemMessages,
      noticeMessages: this.data.noticeMessages,
      commentMessages: this.data.commentMessages,
      likeMessages: this.data.likeMessages
    };
    wx.setStorageSync('volunteerMessagesData', messagesData);
  },

  getCurrentMessages() {
    switch (this.data.activeTab) {
      case 'system':
        return this.data.systemMessages;
      case 'notice':
        return this.data.noticeMessages;
      case 'comment':
        return this.data.commentMessages;
      case 'like':
        return this.data.likeMessages;
      default:
        return [];
    }
  },

  getTabName() {
    const tabNames = {
      system: '系统',
      notice: '通知',
      comment: '评论',
      like: '点赞'
    };
    return tabNames[this.data.activeTab] || '';
  },

  goBack() {
    wx.navigateBack();
  },

  onPullDownRefresh() {
    this.loadMessages();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  onShareAppMessage() {
    return {
      title: '志愿者消息中心',
      path: '/pages/volunteer/messages'
    };
  }
});